<?php

namespace app\common\service\user;

use app\admin\model\user\UserAttention;
use app\common\service\BaseService;

class UserAttentionService extends BaseService
{
    /**
     * Author:Zhongyuan Lu
     * 关注商品
     * @param $uid
     * @param $goods_id
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public static function attention($uid,$goods_id)
    {
        //添加参数
        $params = ['uid' => $uid, 'goods_id' => $goods_id];
        //查询条件
        $where = [
            ['uid', '=', $uid],
            ['goods_id', '=', $goods_id],
        ];

        $model = new UserAttention();
        //查询用户是否关注过此商品
        $data = $model->withTrashed()->where($where)->find();
        if (!$data) {
            //首次关注
            $params['time'] = 1;
            $bool = $model->create($params);
            if($bool) {
                return self::success('关注成功');
            }
            return self::fail('关注失败');
        }

        //已关注 且未被删除  则取消关注
        if (empty($data->delete_time)) {
            $bool = $model->destroy($data->id);
            if($bool) {
                return self::success('取消关注');
            }
            return self::fail('取消关注失败');
        }

        self::beginTrans();
        try {
            //再次关注  恢复数据 关注次数+1
            $data->restore();
            $data->inc('time')->update();

            self::commitTrans();
            return self::success('关注成功');

        } catch (\Exception $e) {
            self::rollbackTrans();
            return self::fail('关注失败');
        }
    }

    /**
     * Author:Zhongyuan Lu
     * 是否首次关注
     * @param $uid
     * @param $goods_id
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public static function isFirstAttention($uid,$goods_id)
    {
        $where = [
            ['uid', '=', $uid],
            ['goods_id', '=', $goods_id],
        ];
        //查询用户是否关注过此商品
        $data = UserAttention::where($where)->find();
        if (!$data) {
            return self::fail('未关注此商品');
        }
        if ($data->time > 1) {
            return self::fail('不是首次关注');
        }
        //首次关注
        return self::success('是首次关注');
    }
}